package io.mft.datasource.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.ds.DataSourceWrapper;
import io.mft.api.domain.Api;
import io.mft.api.domain.DataAccessRegulation;
import io.mft.api.domain.builder.SqlIdBuilder;
import io.mft.commons.config.ConfigProvider;
import io.mft.commons.config.datasource.DSConfigSource;
import io.mft.commons.config.datasource.DatasourceConfig;
import io.mft.commons.db.source.DbProvider;
import io.mft.commons.function.datasource.DatasourceType;
import io.mft.datasource.db.accessor.sql.SQLScript;
import io.mft.datasource.db.accessor.sql.SQLScript.SQLScriptType;
import io.mft.datasource.db.accessor.sql.SQLScriptManager;
import io.mft.dev.base.MFTRuntimeConfig;
import io.mft.dev.base.cat.CatDruidFilter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DbBootstrap {
	public static void init(MFTRuntimeConfig config) {
		config.getApis().forEach(api->{
			registerSQLScript(api);
		});
		
		config.getDsConfig().values().forEach(dsConfigSource->{
			initDb(dsConfigSource);
		});
	}
	
	private static void registerSQLScript(Api api) {
		api.getApiRegulations().stream().forEach(r->{
			if (r.getRegulation() instanceof DataAccessRegulation) {
				DataAccessRegulation dataAccessRegulation=(DataAccessRegulation)r.getRegulation();
				if (dataAccessRegulation.getType().DatasourceType() == DatasourceType.db) {
					String sqlId=SqlIdBuilder.build(api, dataAccessRegulation);
					SQLScript sqlScript = SQLScript.builder().id(sqlId).script(dataAccessRegulation.getValue())
							.type(SQLScriptType.valueOf(dataAccessRegulation.getType().name())).build();
					SQLScriptManager.getInstance().add(sqlScript);
					log.warn("注册SQL->>>id:{}->>>type:{}->>>value:{}",sqlScript.getId(),sqlScript.getType().name(),sqlScript.getScript());
				}
			}

		});
	}
	
	private static void initDb(DSConfigSource dsConfigSource) {
		try {
			if (!"db".equals(dsConfigSource.getType())) {
				return;
			}
			//数据库
			if (dsConfigSource.getDatasources()!=null) {
 				for (DatasourceConfig datasourceConfig : dsConfigSource.getDatasources()) {
					if (ObjectUtil.isNotEmpty(datasourceConfig.getRefDatasoueceId())) {
						DbProvider.getInstance().addRefDatasourceId(datasourceConfig.getId(), datasourceConfig.getRefDatasoueceId());
						continue;
					}
					Map<String, String> config=new HashMap<String, String>();
					datasourceConfig.getConfig().entrySet().forEach(entry->{
						config.put(entry.getKey(), String.valueOf(entry.getValue()));
					});
					boolean s=DbProvider.getInstance().addDatasourceConfig(datasourceConfig.getId(),config);
					if (s) {
						int use= ConfigProvider.get("system.cat.use", 1);
						if (use==1) {
							DataSource dataSource=DbProvider.getInstance().getDataSource(datasourceConfig.getId());
							DataSourceWrapper dataSourceWrapper=(DataSourceWrapper)dataSource;
							if (dataSourceWrapper.getRaw() instanceof DruidDataSource) {
								DruidDataSource druidDataSource=(DruidDataSource)dataSourceWrapper.getRaw();
								List<Filter> filters=new ArrayList<>();
								CatDruidFilter filter=new CatDruidFilter();
								String dbType = druidDataSource.getDriverClassName();
								String url = druidDataSource.getUrl();
								filter.setDbType(dbType);
								filter.setUrl(url);
								filters.add(filter);
								druidDataSource.setProxyFilters(filters);
							}				
						}
						log.warn("注册db数据源:{}",datasourceConfig.getId());
					}
					
				}	
			}
		
		} catch (Throwable e) {
			log.error("",e);
		}

	}
}
